#include "sceneObject.h"
#include <algorithm>

using namespace std;

SceneObject::SceneObject(){
	this->parent=NULL;
}

SceneObject::SceneObject(const ObjectModelPtr& model){
	this->setObjectModel(model);
	this->parent=NULL;
}

SceneObject::SceneObject(const Cube& cube)
	:	dimensions(cube){
	this->parent=NULL;
}

SceneObject::SceneObject(const Cube& cube,const ObjectModelPtr& model)
	:	dimensions(cube){
	this->setObjectModel(model);
	this->parent=NULL;
}

SceneObject::SceneObject(const Point& direction,const ObjectModelPtr& model){
	this->setDirection(direction);
	this->setObjectModel(model);
	this->parent=NULL;
}

SceneObject::SceneObject(const Point& direction){
	this->setDirection(direction);
	this->parent=NULL;
}


SceneObject::SceneObject(const Cube& cube,const Point& direction)
	:	dimensions(cube){
	this->setDirection(direction);
	this->parent=NULL;
}

SceneObject::SceneObject(const Cube& cube,const Point& direction,const ObjectModelPtr& model)
	: 	dimensions(cube){
	this->setDirection(direction);
	this->setObjectModel(model);
	this->parent=NULL;
}

SceneObject::~SceneObject(){
	for (map<std::string,SceneObject*>::iterator it=listObject.begin();it!=listObject.end();++it)
		delete(it->second);
}

void SceneObject::addObject(const std::string& name,SceneObject* obj){
	listObject.insert( std::make_pair(name,obj) );
}

void SceneObject::removeObject(const std::string& name){
	map<std::string,SceneObject*>::iterator it= listObject.find(name);
	if (it==listObject.end())
		return;
	delete (it->second);
	listObject.erase(it);
}

SceneObject& SceneObject::findObject(const std::string& name)const{
	return *listObject.find(name)->second;
}

SceneObject* SceneObject::getObject(const std::string& name){
	map<std::string,SceneObject*>::iterator it= listObject.find(name);
	if (it==listObject.end())
		return NULL;
	SceneObject* ret = (it->second);
	listObject.erase(it);
	return ret;
}

void SceneObject::setModelMatrix(){
	Point tr = this->dimensions.center();
	glTranslatef(tr.x1,tr.x2,tr.x3);
	glScalef(this->dimensions.width(),this->dimensions.depth(),this->dimensions.height());
}

void SceneObject::setSubModelMatrix(const std::string& name){}

void SceneObject::setDirection(const Point& point){
	float mod = point.mod();

	if(mod!=1.0f && mod!=0){
		this->direction = point*(1/mod);
	}else
		this->direction = point;
}
